package dialer.client.web.controlador;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.SessionScoped;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.primefaces.event.FlowEvent;

import dialer.ws.base.entity.Form;
import dialer.ws.base.entity.FormField;
import dialer.ws.base.entity.Item;
import dialer.ws.base.exception.EntityException;
import dialer.ws.base.exception.EntityExistException;
import dialer.ws.business.service.FormFieldService;
import dialer.ws.business.service.FormService;
import dialer.ws.common.util.FacesUtils;

@ManagedBean(name = "form")
@SessionScoped
public class FormController implements Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = 4820537140705088871L;

	private static final Log log = LogFactory.getLog(FormController.class);

	private boolean skip;
	private boolean viewListDetail;
	private boolean viewButtonEdit;

	private String estado;
	private String nombre;
	private String descripcion;
	private String etiqueta;
	private String tipo;

	private List<Item> items = new ArrayList<Item>();
	private List<Item> itemsTipificacion = new ArrayList<Item>();
	private List<Form> listForm = new ArrayList<Form>();
	private List<FormField> listCampo = new ArrayList<FormField>();

	private Item itemTipificacion = new Item();
	private Item item = new Item();
	private Form selectedForm = new Form();
	private FormField selectedCampo = new FormField();

	@ManagedProperty("#{formService}")
	private FormService formService;

	@ManagedProperty("#{formFieldService}")
	private FormFieldService formFieldService;

	public FormController() {
		clear();
	}

	@PostConstruct
	public void init() {
		listForm = formService.findAll();
	}

	public void actualizarLista() {
		log.info("### actualizarLista" + estado);
		if (estado != null && !estado.equals("")) {
			if (estado.equals("*")) {
				listForm = formService.findAll();
			} else {
				listForm = formService.getFormByState(estado);
			}
		}
	}

	public void reinitTipificacion() {
		log.info("### reinitTipificacion");
		itemTipificacion = new Item();
	}

	public void reinit() {
		log.info("### reinit");
		item = new Item();
	}

	public void viewList1() {
		log.info("### viewList1 " + tipo);
		if (tipo.equals("LIST")) {
			viewListDetail = true;
		} else {
			viewListDetail = false;
		}
	}

	public void viewList2() {
		log.info("### viewList2 " + selectedCampo.getTipo());
		if (selectedCampo.getTipo().equals("LIST")) {
			viewListDetail = true;
		} else {
			viewListDetail = false;
		}
	}

	public String onFlowProcess(FlowEvent event) {
		log.info("### Current wizard step:" + event.getOldStep());
		log.info("### Next step:" + event.getNewStep());
		return event.getNewStep();
	}

	public void load() {
		log.info("### load " + selectedForm.getId());
		clearPanelTipificacion();
		clearPanelCampos();
		listCampo = formFieldService.getFormFieldById(selectedForm.getId());
		String[] aaa = listCampo.get(0).getValue().split(",");
		for (int i = 0; i < aaa.length; i++) {
			Item it = new Item();
			it.setNombre((String) aaa[i]);
			itemsTipificacion.add(it);
		}
	}

	public void loadCamposForEdit() {
		log.info("### loadCamposForEdit " + selectedCampo.getTipo());
		viewButtonEdit = true;
		items.clear();
		if (selectedCampo.getTipo().equals("LIST")) {
			String[] aaa = selectedCampo.getValue().split(",");
			for (int i = 0; i < aaa.length; i++) {
				Item it = new Item();
				it.setNombre((String) aaa[i]);
				items.add(it);
			}
			viewListDetail = true;
		} else {
			viewListDetail = false;
		}
	}

	public void addCampo() {
		log.info("### guardarCampos");
		FormField ff = new FormField();
		ff.setEtiqueta(etiqueta);
		ff.setTipo(tipo);
		if (tipo.equals("LIST")) {
			String value = "";
			for (Item it : items) {
				value = value + it.getNombre() + ",";
			}
			ff.setValue(value);
		} else {
			ff.setValue("");
		}
		listCampo.add(ff);
		clearPanelCampos();
	}

	public void refreshCampo() {
		log.info("### refreshCampo");
		if (selectedCampo.getTipo().equals("LIST")) {
			String value = "";
			for (Item it : items) {
				value = value + it.getNombre() + ",";
			}
			log.info("### value " + value);
			listCampo.get(selectedCampo.getOrden() - 1).setValue(value);
		} else {
			listCampo.get(selectedCampo.getOrden() - 1).setValue("");
		}
		clearPanelCampos();
	}

	public void clearPanelTipificacion() {
		itemTipificacion = new Item();
		itemsTipificacion.clear();
	}

	public void clearPanelCampos() {
		etiqueta = "";
		tipo = "TEXT";
		selectedCampo = new FormField();
		item = new Item();
		items.clear();
		viewListDetail = false;
		viewButtonEdit = false;
	}

	public void guardar() {
		log.info("### guardarFormulario");
		Form f = new Form();
		f.setNombre(nombre);
		f.setDescripcion(descripcion);
		f.setEstatus("A");

		int i = 1;
		for (FormField aux : listCampo) {
			aux.setForm(f);
			aux.setOrden(1 + i);
			if (aux.getTipo().equals("LIST")) {
				String value2 = "";
				for (Item it : items) {
					value2 = value2 + it.getNombre() + ",";
				}
				aux.setValue(value2);
			} else {
				aux.setValue("");
			}
			i++;
		}

		FormField ff = new FormField();
		ff.setForm(f);
		ff.setOrden(1);
		ff.setEtiqueta("Tipificacion");
		ff.setTipo("LIST");
		String value = "";
		for (Item it : itemsTipificacion) {
			value = value + it.getNombre() + ",";
		}
		ff.setValue(value);
		listCampo.add(0, ff);

		f.setListFormField(listCampo);
		try {
			formService.persist(f);
			clear();
			init();
			FacesUtils.addInfoMessage("Satisfactorio", "se guardo correctamente");
		} catch (EntityExistException e) {
			log.error("### ERROR: " + e);
			FacesUtils.addErrorMessage("Error", "no se guardo correctamente");
		} catch (EntityException e) {
			log.error("### ERROR: " + e);
			FacesUtils.addErrorMessage("Error", "no se guardo correctamente");
		}
	}

	public void editar() {
		log.info("### editar");
		Form f = new Form();
		f.setId(selectedForm.getId());
		f.setNombre(selectedForm.getNombre());
		f.setDescripcion(selectedForm.getDescripcion());
		f.setEstatus(selectedForm.getEstatus());
		int i = 1;
		for (FormField aux : listCampo) {
			aux.setForm(f);
			if (i == 1) {
				if (!itemsTipificacion.isEmpty()) {
					for (Item it : itemsTipificacion) {
						aux.setValue(it.getNombre() + ",");
					}
				}
			}
			aux.setOrden(i);
			if (!items.isEmpty()) {
				for (Item it : items) {
					aux.setValue(it.getNombre() + ",");
				}
			} else {
				aux.setValue("");
			}
			i++;
		}

		f.setListFormField(listCampo);
		try {
			formService.merge(f);
			clear();
			init();
			FacesUtils.addInfoMessage("Satisfactorio", "se guardo correctamente");
		} catch (EntityException e) {
			log.error("### ERROR: " + e);
			FacesUtils.addErrorMessage("Error", "no se guardo correctamente");
		}
	}

	public void activar() {
		log.info("### activarFormulario");
		if (!selectedForm.getEstatus().equals("A")) {
			selectedForm.setEstatus("A");
			try {
				formService.merge(selectedForm);
				FacesUtils.addInfoMessage("Satisfactorio", "se activo correctamente");
			} catch (EntityException e) {
				log.error("### ERROR: " + e);
				FacesUtils.addErrorMessage("Error", "error");
			}
		}
	}

	public void desactivar() {
		log.info("### desactivar");
		if (!selectedForm.getEstatus().equals("I")) {
			selectedForm.setEstatus("I");
			try {
				formService.merge(selectedForm);
				FacesUtils.addInfoMessage("Satisfactorio", "se desactivo correctamente");
			} catch (EntityException e) {
				log.error("### ERROR: " + e);
				FacesUtils.addErrorMessage("Error", "error");
			}
		}
	}

	public void view() {
		log.info("### viewFormulario");
	}

	public void eliminar() {
		log.info("### eliminarFormulario");
		selectedForm.setEstatus("E");
		try {
			formService.merge(selectedForm);
			FacesUtils.addInfoMessage("Satisfactorio", "se elimino correctamente");
		} catch (EntityException e) {
			log.error("### ERROR: " + e);
			FacesUtils.addErrorMessage("Error", "error");
		}
	}

	public void clear() {
		log.info("### clear");
		skip = false;
		viewListDetail = false;

		estado = "";
		nombre = "";
		descripcion = "";
		etiqueta = "";
		tipo = "TEXT";

		items.clear();
		itemsTipificacion.clear();
		listForm.clear();
		listCampo.clear();

		item = new Item();
		itemTipificacion = new Item();
		selectedForm = new Form();
		selectedCampo = new FormField();
	}

	public String getEstado() {
		return estado;
	}

	public void setEstado(String estado) {
		this.estado = estado;
	}

	public List<Form> getListForm() {
		return listForm;
	}

	public void setListForm(List<Form> listForm) {
		this.listForm = listForm;
	}

	public Form getSelectedForm() {
		return selectedForm;
	}

	public void setSelectedForm(Form selectedForm) {
		this.selectedForm = selectedForm;
	}

	public FormService getFormService() {
		return formService;
	}

	public void setFormService(FormService formService) {
		this.formService = formService;
	}

	public boolean isSkip() {
		return skip;
	}

	public void setSkip(boolean skip) {
		this.skip = skip;
	}

	public String getNombre() {
		return nombre;
	}

	public void setNombre(String nombre) {
		this.nombre = nombre;
	}

	public String getDescripcion() {
		return descripcion;
	}

	public void setDescripcion(String descripcion) {
		this.descripcion = descripcion;
	}

	public String getEtiqueta() {
		return etiqueta;
	}

	public void setEtiqueta(String etiqueta) {
		this.etiqueta = etiqueta;
	}

	public String getTipo() {
		return tipo;
	}

	public void setTipo(String tipo) {
		this.tipo = tipo;
	}

	public List<FormField> getListCampo() {
		return listCampo;
	}

	public void setListCampo(List<FormField> listCampo) {
		this.listCampo = listCampo;
	}

	public FormField getSelectedCampo() {
		return selectedCampo;
	}

	public void setSelectedCampo(FormField selectedCampo) {
		this.selectedCampo = selectedCampo;
	}

	public boolean isViewListDetail() {
		return viewListDetail;
	}

	public void setViewListDetail(boolean viewListDetail) {
		this.viewListDetail = viewListDetail;
	}

	public Item getItem() {
		return item;
	}

	public void setItem(Item item) {
		this.item = item;
	}

	public List<Item> getItems() {
		return items;
	}

	public void setItems(List<Item> items) {
		this.items = items;
	}

	public FormFieldService getFormFieldService() {
		return formFieldService;
	}

	public void setFormFieldService(FormFieldService formFieldService) {
		this.formFieldService = formFieldService;
	}

	public List<Item> getItemsTipificacion() {
		return itemsTipificacion;
	}

	public void setItemsTipificacion(List<Item> itemsTipificacion) {
		this.itemsTipificacion = itemsTipificacion;
	}

	public Item getItemTipificacion() {
		return itemTipificacion;
	}

	public void setItemTipificacion(Item itemTipificacion) {
		this.itemTipificacion = itemTipificacion;
	}

	public boolean isViewButtonEdit() {
		return viewButtonEdit;
	}

	public void setViewButtonEdit(boolean viewButtonEdit) {
		this.viewButtonEdit = viewButtonEdit;
	}

}
